"""
漏斗图：适用于业务流程环节多的流程分析，通过漏斗各环节业务数据的比较，能够直观地发现问题所在。

实例：数据来自kaggle网站的"E-commerce website Funnel analysis"
地址为：https://www.kaggle.com/aerodinamicc/ecommerce-website-funnel-analysis

网站很简单，有四个页面数据：

home_page_table.csv，首页用户访问数据
search_page_table.csv，搜索页用户访问数据
payment_page_table.csv，支付信息页用户访问数据
payment_confirmation_table.csv，支付成功页用户访问数据
user_table.csv，用户信息数据
目标：绘制转化漏斗，查看是否正常
"""
import pandas as pd

from pyecharts.charts import Funnel
from pyecharts import options as opts

# 1.读取数据
df_home_page = pd.read_csv('./Files/ecommerce-website-funnel-analysis/home_page_table.csv')
df_search_page = pd.read_csv('./Files/ecommerce-website-funnel-analysis/search_page_table.csv')
df_payment_page = pd.read_csv('./Files/ecommerce-website-funnel-analysis/payment_page_table.csv')
df_payment_confirmation_page = pd.read_csv('./Files/ecommerce-website-funnel-analysis/payment_confirmation_table.csv')
df_user_table = pd.read_csv('./Files/ecommerce-website-funnel-analysis/user_table.csv')

# 2.将数据合并成一个大表。合并之前各表中的重复列名修改，否则新版Python的Merge会报错
df_home_page.rename(columns={"page": "home_page"}, inplace=True)
df_search_page.rename(columns={"page": "search_page"}, inplace=True)
df_payment_page.rename(columns={"page": "payment_page"}, inplace=True)
df_payment_confirmation_page.rename(columns={"page": "confirmation_page"}, inplace=True)

df_merge = df_user_table

for df_inter in [df_home_page, df_search_page, df_payment_page, df_payment_confirmation_page]:
    df_merge = pd.merge(
        left=df_merge,
        right=df_inter,
        left_on='user_id',
        right_on='user_id',
        how='left',
        suffixes=('_1', '_2')
    )
# df_merge.columns = ["user_id", "date", "device", "sex", "home_page", "search_page", "payment_page", "confirmation_page"]

# print(df_merge.head())

# 3.计算每个页面的用户数目
# 目的是给漏斗图填充数据，pyecharts需要的格式为：数据格式为[(key1, value1), (key2, value2)]
datas = []
for column in ["home_page", "search_page", "payment_page", "confirmation_page"]:
    user_count = df_merge[column].dropna().size
    datas.append((column, user_count))
# print(datas)

# 方便查看对比，进行归一化（即，找出最大的数据，在等比例缩小）
max_num = datas[0][1]
datas_norm = [(x, round(y * 100 / max_num, 2)) for (x, y) in datas]
# print(datas_norm)

# 4. 绘制漏斗图
funnel = Funnel().set_global_opts(opts.TitleOpts(title="用户转化率漏洞图"))
funnel.add(series_name="用户比例", data_pair=datas_norm)
funnel.render(path='./Files/my_funnel.html')
